import React, {useState, useEffect} from 'react'
import { Dropdown, Menu, Space, message } from 'antd';
import { CaretDownOutlined } from '@ant-design/icons';
import {useNavigate} from 'react-router-dom'
import logoImg from '../assets/images/logo.png'
import defaultAvatar from '../assets/images/defaultAvatar.png'

export default function Header() {
  const navigate = useNavigate()
  const [avatar, setAvatar] = useState(defaultAvatar)
  const [username, setUsername] = useState('游客')
  // 模拟componentDidMount
  useEffect(()=>{
    let localUsername = localStorage.getItem('username')
    let localAvatar = localStorage.getItem('avatar')
    if(localUsername){
      setUsername(localUsername)
    }
    if(localAvatar){
      setAvatar('http://47.93.114.103:6688/'+localAvatar)
    } 
  },[])
  const onMenu = ({ key }) =>{
    if(key === '2'){
      message.success('退出成功，即将返回登录页')
      // localStorage.clear(); // 清除localStorage中的数据
      localStorage.removeItem('avatar');
      localStorage.removeItem('cms-token');
      localStorage.removeItem('editable');
      localStorage.removeItem('player');
      localStorage.removeItem('username');
      setTimeout(() => {
        navigate('/login')
      }, 1500);
    }
  }
  const menu = (
    <Menu
      onClick={onMenu}
      items={[
        {
          key: '1',
          label: '修改资料',
        },
        {
          type: 'divider',
        },
        {
          key: '2',
          label: '退出登录',
        },
      ]}
    />
    // <Menu>
    //   <Menu.Item>修改资料</Menu.Item>
    //   <Menu.Divider/>
    //   <Menu.Item>退出登录</Menu.Item>
    // </Menu>
  );
  return (
    <header>
        <img src={logoImg} alt="" className="logo" />
        <div className="right">
          <Dropdown overlay={menu}>
            {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
            <a onClick={(e) => e.preventDefault()} className="ant-dropdown-link">
            <Space>
              <img src={avatar} alt="" className='avatar'/>
              <span>{username}</span>
              <CaretDownOutlined />
            </Space>
            </a>
          </Dropdown>
        </div>
    </header>
  )
}
